import React, { useEffect, useState } from 'react';
import { LoginOutlined, UserOutlined } from '@ant-design/icons';
import {
  message,
  Button,
  Space,
  Card,
  List,
  Avatar,
  Steps,
  Modal,
  Row,
  Col,
  Table,
  Input,
} from 'antd';
import FormRender, { useForm } from 'form-render';
import { usrColumns } from './data';
import SearchTree from '../../components/SearchTree';
import { flowableToFormEngine } from '../../utils/formSchemaTransform';
import {
  startProcessInstanceWithForm,
  getProcessDefinitionTaskFormData,
} from '../../services/processFormRepository';
import { getHistoryActInst } from '../../services/processTask';
import {
  getTasksByUser,
  delegateTask,
  transfer,
  flowTackback,
  complete,
  getAllNode,
  getActInstList,
} from '../../services/todoTask';
import { getOrgTree, getUser } from '../../services/upmsServices';

const { TextArea } = Input;

const TaskProcessing = (props: any) => {
  const { processingModelCancel } = props;
  // 绑定渲染表单
  const renderForm = useForm();
  // 节点信息
  const [nodesInfo, setNodesInfo] = useState([{}]);
  // 节点过程
  const [current, setCurrent] = useState(1);
  // 动态表单
  const [formSchema, setFormSchema] = useState<{} | null>({});
  // 意见信息
  const [opinionData, setOpinionData] = useState([]);
  // 委派或转办
  const [type, setType] = React.useState('');
  // 控制委派转办弹框
  const [delegateModel, setDelegateModel] = useState(false);
  // 树数据
  const [orgTree, setOrgTree] = useState([]);
  // 组织id
  const [orgId, setOrgId] = useState<string>('');
  // 表格数据
  const [tableData, setTableData] = useState([]);
  // 审批人key
  const [approversKey, setApproversKey] = useState<React.Key[]>([]);
  // 审批意见
  const [approvalOpinions, setApprovalOpinion] = useState('');
  // 控制驳回弹框
  const [rejectModel, setRejectModel] = useState(false);
  // 驳回原因
  const [reject, setReject] = useState('');

  useEffect(() => {
    init();
  }, []);

  // 初始化页面
  const init = async () => {
    // 获取流程信息
    let itemInfo = props.itemInfo;
    console.log(itemInfo);
    if (itemInfo) {
      // 获取本节点表单表单
      let formRes = await getProcessDefinitionTaskFormData({
        taskId: itemInfo.id,
      });
      console.log(formRes);
      // 有表单则渲染表单
      if (formRes.data != '') {
        let obj = flowableToFormEngine(formRes.data);
        setFormSchema(obj);
      } else {
        setFormSchema(null);
      }
      // 查询流程信息
      if (itemInfo.processInstanceId) {
        // 查询历史节点信息
        let res = await getActInstList({
          processInstanceId: itemInfo.processInstanceId,
        });
        console.log(res);
        if (res.code !== '000000') {
          return message.error('获取流程信息失败');
        }
        setCurrent(res.data.length - 1);
        let opinion = res.data.filter(
          (item: any, index: number) =>
            item.activityType !== 'sequenceFlow' &&
            index !== res.data.length - 1,
        );
        setOpinionData(opinion);
        // 查询全部节点信息
        let nodeRes = await getAllNode({
          processDefinitionId: itemInfo.processDefinitionId,
        });
        console.log(nodeRes);
        if (nodeRes.code !== '000000') {
          return message.error('获取流程信息失败');
        }
        let nodes = nodeRes.data.map((item: any) => {
          return {
            title: item.name,
          };
        });
        for (var i = 0; i < nodeRes.data.length; i++) {
          let obj = { title: '', description: <></> };
          for (var n = 0; n < res.data.length; n++) {
            if (nodeRes.data[i].id === res.data[n].activityId) {
              obj.title = nodeRes.data[i].name;
              obj.description = (
                <>
                  <p style={{ fontSize: 12, margin: 0 }}>
                    {res.data[n].startTime}{' '}
                  </p>
                  <p style={{ fontSize: 12, margin: 0 }}>
                    {res.data[n].assignee}
                  </p>
                </>
              );
              nodes[i] = obj;
            } else {
            }
          }
        }
        console.log(nodes);
        setNodesInfo(nodes);
      }
    }
  };

  // 获取机构树
  const getOrgList = async () => {
    let res = await getOrgTree({});
    if (res.code !== '000000') {
      message.error('获取机构信息失败');
      return;
    }
    setOrgTree(setTree(res.data));
  };

  // 打造机构树
  const setTree = (arr: any) => {
    let tree = arr.map((item: any) => {
      let obj = {
        title: item.orgName,
        key: item.orgId,
        children: [],
      };
      if (item.children.length !== 0) {
        obj.children = setTree(item.children);
      }
      return obj;
    });
    return tree;
  };

  // 表格勾选函数
  const onSelectChange = (selectedRowKeys: React.Key[]) => {
    setApproversKey(selectedRowKeys);
  };

  // 表格配置
  const rowSelection = {
    selectedRowKeys: approversKey,
    onChange: onSelectChange,
  };

  // 获取表格数据
  const getTableData = async (orgId: string) => {
    setOrgId(orgId);
    let res = await getUser({ orgId });
    if (res.code !== '000000') {
      message.error('获取审批人表格失败');
      return;
    }
    setTableData(res.data);
  };

  // 任务委派/转办确认
  const handleOk = async () => {
    if (type == '委派') {
      let res = await delegateTask({
        taskId: props.itemInfo?.id,
        assignee: approversKey[0],
      });
      console.log(res);
      if (res.code == '000000') {
        message.success('委派任务成功');
      } else {
        message.error('委派任务失败');
      }
    } else if (type == '转办') {
      let res = await transfer({
        taskId: props.itemInfo?.id,
        assignee: approversKey[0],
      });
      console.log(res);
      if (res.code == '000000') {
        message.success('转办任务成功');
      } else {
        message.error('转办任务失败');
      }
    }
    processingModelCancel();
    setDelegateModel(false);
    setApproversKey([]);
    setOrgId('');
  };

  // 任务委派/转办取消
  const handleCancel = () => {
    setDelegateModel(false);
  };

  // 审批意见改变时调用
  const onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setApprovalOpinion(e.target.value);
  };

  // 任务完成
  const completedTask = async () => {
    console.log(renderForm.getValues());
    console.log(renderForm.formData);
    let res = await complete({
      variables: {
        ...renderForm.formData,
        approvalOpinion: approvalOpinions,
      },
      taskId: props.itemInfo.id,
    });
    processingModelCancel();
    setApprovalOpinion('');
    if (res.code != '000000') {
      return message.error('处理失败');
    }
    message.success('处理成功');
  };

  // 驳回确定
  const rejectOk = async () => {
    let res = await flowTackback({
      comment: reject,
      taskId: props.itemInfo.id,
    });
    console.log(res);
    setRejectModel(false);
    processingModelCancel();
    if (res.code != '000000') {
      return message.error('驳回失败');
    }
    message.success('驳回成功');
  };

  // 驳回取消
  const rejectCancel = () => {
    setRejectModel(false);
  };

  // 驳回输入框改变
  const rejectChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setReject(e.target.value);
  };

  return (
    <div>
      <Card>
        <Steps progressDot current={current} items={nodesInfo} />
      </Card>
      <Card title="意见信息" style={{ marginTop: 10 }}>
        <List
          itemLayout="horizontal"
          dataSource={opinionData}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <p>
                    {item.assignee} {item.endTime}
                  </p>
                }
                description={item.approvalOpinion}
              />
            </List.Item>
          )}
        />
      </Card>
      <Card title="审批" style={{ marginTop: 10 }}>
        {formSchema ? (
          <FormRender form={renderForm} schema={formSchema} />
        ) : (
          <TextArea
            showCount
            maxLength={100}
            placeholder="请填写审批意见"
            onChange={onChange}
          />
        )}
      </Card>
      <Space wrap style={{ marginTop: 10 }}>
        <Button type="primary" onClick={completedTask}>
          任务完成
        </Button>
        <Button
          type="primary"
          onClick={() => {
            setRejectModel(true);
          }}
        >
          任务驳回
        </Button>
        <Button
          type="primary"
          onClick={() => {
            getOrgList();
            setDelegateModel(true);
            setType('委派');
          }}
        >
          任务委派
        </Button>
        <Button
          type="primary"
          onClick={() => {
            getOrgList();
            setDelegateModel(true);
            setType('转办');
          }}
        >
          任务转办
        </Button>
      </Space>
      <Modal
        title={`选择${type}人`}
        open={delegateModel}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Row gutter={16} style={{ marginTop: 10 }}>
          <Col span={6}>
            <SearchTree
              // 渲染数据
              checkedId={orgId}
              treeData={orgTree}
              changeKey={getTableData}
            />
          </Col>
          <Col span={18}>
            <Table
              rowSelection={{
                type: 'radio',
                ...rowSelection,
              }}
              columns={usrColumns}
              dataSource={tableData}
              rowKey="userId"
            />
          </Col>
        </Row>
      </Modal>
      <Modal
        title="驳回原因"
        open={rejectModel}
        onOk={rejectOk}
        onCancel={rejectCancel}
      >
        <TextArea
          showCount
          maxLength={100}
          placeholder="请填写驳回原因"
          onChange={rejectChange}
        />
      </Modal>
    </div>
  );
};

export default TaskProcessing;
